<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 更新参与日志-投票活动
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300200_100046_t_activity_attend_log_vote extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%activity_attend_log}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from('{{%activity_user_vote}}')->andWhere([
            'type' => 'vote',
        ])->orderBy([
            'created_at' => SORT_ASC
        ])->groupBy(['user_id']);
        $this->handleProgress($query, [$this, 'evenDule'], null, Yii::$app->olddb);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        $connect = $migration->db->createCommand();
        $items = [];
        foreach ($rows as $row) {
            $items[] = [
                'activity_id' => $row['actid'],
                'user_id' => $row['user_id'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
            ];
        }
        if (empty($items)) {
            return;
        }
        $connect->batchInsert('{{%activity_attend_log}}', [
            'activity_id',
            'user_id',
            'created_at',
            'updated_at',
        ], $items)->execute();
    }

}
